package week2.Chapter3;

import java.util.Arrays;

/**
 * An array implementation of a stack  in which the bottom of the
 * stack is fixed  at index 0.
 *
 * 课堂作业
 * @author Lewis and Chase
 * @version 4.0
 */
public class ArrayStack<T> extends java.util.Stack<T> {
    private final int DEFAULT_CAPACITY = 100;

    private int top;
    private T[] Stack;

    /*使用默认容量创建一个空栈*/
    public ArrayStack()
    {
        top = 0;
        Stack = (T[])(new Object[DEFAULT_CAPACITY]);
    }

    /*使用指定容量创建一个空栈，参数initialCapacity表示的是指定容量*/
    public ArrayStack(int initialCapacity){
        top = 0;
        Stack = (T[]) (new Object[initialCapacity]);
    }

    /**
     * Adds the specified element to the top of this stack, expanding
     * the capacity of the array if nessary.
     * @param element generic element to be pushed onto stack.
     */
    @Override
    public T push(T element){
        if(size()==Stack.length) {
            expandCapacity();
        }
        Stack[top] = element;
        top++;
        return element;
    }

    /**
     * Create a new array to store the contents of this stack with
     * twice the capacity of the old one.
     */
    private void expandCapacity(){
        Stack= Arrays.copyOf(Stack,Stack.length*2);
    }

    /**
     * Remove the element at the top of this stack and return a
     * reference to it.
     * @return element removed from top of stack
     * @throws EmptyCollectionException if stack is empty
     */
    @Override
    public T pop() throws EmptyCollectionException
    {
        if (isEmpty()) {
            throw new EmptyCollectionException("Stack");
        }
        top--;
        T result = Stack[top];
        Stack[top] = null;

        return result;
    }

    /**
     * Returns a reference to the element at the top of this stack.
     * The element is not removed from the stack.
     * @return element on top of stack
     * @throws EmptyCollectionException if stack is empty
     */
    @Override
    public T peek() throws  EmptyCollectionException
    {
        if (isEmpty()) {
            throw new  EmptyCollectionException("Stack");
        }
        return Stack[top-1];
    }
    @Override
    public boolean isEmpty(){
        if(size()==0) {
            return true;
        } else {
            return false;
        }
    }
    @Override
    public int size(){
        return this.top;
    }
    @Override
    public String toString() {
        String result = "栈顶\t";

        for(int index = this.top - 1; index >= 0; index--) {
            result = result + this.Stack[index] + "\t";
        }
        return result + "栈底";
    }
}
